package dao

import (
	"activity_srv/model"
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"log"
	model2 "order_srv/model"
	"smart-health-platforms/pkg"
	"time"
)

// 用于存储用户的分销关系链，确定佣金分配对象，一级分销用户，二级分销用户
type UserDistributionRelations struct {
	FirstLevelUserID  uint32 `json:"first_level_user_id"`  //一级分销用户,上一级
	SecondLevelUserID uint32 `json:"second_level_user_id"` //二级分销用户,上上级
}

// 分销关系查询,查询用户是否在分销体系中
func GetUserDistributionRelations(userId int64) (*UserDistributionRelations, error) {
	relations := &UserDistributionRelations{}
	// 1. 查询当前用户的分销信息
	var currentUser model.DistributionUser
	if err := currentUser.GetUserId(userId); err != nil {
		pkg.Error("查询用户分销信息失败", zap.Error(err), zap.Int64("userId", userId))
		return nil, err
	}
	if currentUser.Id == 0 {
		pkg.Info("用户未参与分销体系", zap.Int64("userId", userId))
		return relations, nil
	}
	// 如果没有上级，直接返回
	if currentUser.ParentId == 0 {
		return relations, nil
	}
	// 2. 一级分销用户就是直接上级
	relations.FirstLevelUserID = currentUser.ParentId

	// 3. 查询一级用户的上级（二级分销用户）
	var firstLevelUser model.DistributionUser
	if err := firstLevelUser.GetUserId(int64(currentUser.ParentId)); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			pkg.Info("二级分销用户不存在", zap.Uint32("firstLevelUserId", currentUser.ParentId))
			return relations, nil
		}
		pkg.Error("查询二级分销用户失败", zap.Error(err))
		return nil, err
	}
	// 如果一级用户有上级，设置二级分销用户
	if firstLevelUser.ParentId > 0 {
		relations.SecondLevelUserID = firstLevelUser.ParentId
	}
	return relations, nil
}

// 处理分销流水
func DistributionOrder(tx *gorm.DB, order *model2.Order) error {
	//获取分销配置,用于计算分销金额
	var distributionConfig model.DistributionSetting
	if err := distributionConfig.Get(); err != nil {
		pkg.Error("获取分销配置失败", zap.Error(err))
		return err
	}
	//查询用户分销关系,判断用户的分销关系,确定哪些用户可以获得佣金
	userRelations, err := GetUserDistributionRelations(int64(order.UserId))
	if err != nil {
		pkg.Error("获取用户分销关系失败", zap.Error(err))
		return err
	}
	// 创建分销流水记录,根据订单金额和分销配置,计算一级分销用户和二级分销用户的佣金
	flows := make([]*model.DistributionCommission, 0)
	// 一级分销
	if userRelations.FirstLevelUserID > 0 { //当前用户有一级分销用户
		firstLevelFlow := &model.DistributionCommission{
			OrderSn:     order.OrderSn,
			OrderAmount: order.TotalPrice,
			UserId:      order.UserId,
			ToUserId:    userRelations.FirstLevelUserID,
			Amount:      order.TotalPrice * distributionConfig.FirstLevelRatio,
			Level:       1,
			CreatedAt:   time.Now(),
		}
		flows = append(flows, firstLevelFlow)
	}
	// 二级分销
	if userRelations.SecondLevelUserID > 0 { //当前用户有二级分销用户
		secondLevelFlow := &model.DistributionCommission{
			OrderSn:     order.OrderSn,
			OrderAmount: order.TotalPrice,
			UserId:      order.UserId,
			ToUserId:    userRelations.SecondLevelUserID,
			Amount:      order.TotalPrice * distributionConfig.SecondLevelRatio,
			Level:       2,
			CreatedAt:   time.Now(),
		}
		flows = append(flows, secondLevelFlow)
	}
	log.Println(order)
	// 批量保存分销流水,将分配佣金的用户和金额保存到分销流水表
	var distributionCommission model.DistributionCommission
	if len(flows) > 0 { //当前用户有分销用户
		if err = distributionCommission.BatchCreate(flows); err != nil { //添加分销流水记录
			pkg.Error("创建分销流水失败", zap.Error(err))
			return err
		}
	}
	pkg.Info("创建分销流水成功", zap.Int("count", len(flows)), zap.Any("flows", flows))
	return err
}
